package csu.jpetstore.jpetstore.utils;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.model.ObjectMetadata;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.Objects;
import java.util.UUID;

public class OSSUtils {
    private OSSUtils(){}

    /**
     * oss 工具客户端
     */
    private volatile static OSS ossClient = null;

    /**
     * 上传文件至阿里云 OSS
     * 文件上传成功,返回文件完整访问路径
     * 文件上传失败,返回 null
     * @author jiangpengcheng
     * @param file 待上传文件
     * @param fileDir 文件保存目录
     * @return oss 中的相对文件路径
     */

    public static String upload(MultipartFile file, String fileDir, String contentType){
        initOSS();
        StringBuilder fileUrl = new StringBuilder();
        try {
            String suffix = Objects.requireNonNull(file.getOriginalFilename()).substring(file.getOriginalFilename().lastIndexOf('.'));
            String fileName = System.currentTimeMillis() + "-" + UUID.randomUUID().toString().substring(0,18) + suffix;
            if (!fileDir.endsWith("/")) {
                fileDir = fileDir.concat("/");
            }
            fileUrl.append(fileDir).append(fileName);
            ObjectMetadata objectMetadata = new ObjectMetadata();
            objectMetadata.setContentType(contentType);
            ossClient.putObject("roadblock-chen", fileUrl.toString(), file.getInputStream(),objectMetadata);
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }
        fileUrl.insert(0, "roadblock-chen.oss-cn-shanghai.aliyuncs.com");
        return fileUrl.toString();
    }

    /**
     * 初始化 oss 客户端
     *
     *
     */
    private static void initOSS() {
        if (ossClient == null ) {
            synchronized (OSSUtils.class) {
                if (ossClient == null) {
                    ossClient = new OSSClientBuilder().build("oss-cn-shanghai.aliyuncs.com", "LTAI4G36sRzEjKXKwR6EvKhe", "NqpYfLTf4XRhLLtKFwh24SxFqr2F3z");
                }
            }
        }
    }

}
